package com.xingtai.db;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;

import com.xingtai.util.Utilities;


public class ConnectionManager implements Serializable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Logger logger = 
        Logger.getLogger("com.runstone.rssmc.ConnectionManager");
    private static DataSource ds = null;
     
    public ConnectionManager(){
    	if(ds == null ){
	    	try{
	    		init();
	    	}catch(Exception ex){
	    		logger.fatal("初始化连接池数据源失败！", ex);
	    	}
    	}
    }
    
    public void init() throws Exception {
    	Properties props = Utilities.loadParams("config");
    	PoolProperties p = new PoolProperties();
        
        p.setUrl(props.get("url").toString());
        p.setDriverClassName(props.get("drivers").toString());
        p.setUsername(props.get("db_user").toString());
        p.setPassword(props.get("db_passwd").toString());
        p.setJmxEnabled(true);
        p.setTestWhileIdle(true);
        p.setTestOnBorrow(true);
        p.setValidationQuery("SELECT 1");
        p.setTestOnReturn(false);
        p.setValidationInterval(30000);
        p.setTimeBetweenEvictionRunsMillis(30000);
        p.setMaxActive(Integer.parseInt(props.get("db_maxActive").toString()));
        p.setInitialSize(50);
        p.setMaxWait(Integer.parseInt(props.get("db_maxWait").toString()));
        p.setRemoveAbandonedTimeout(Integer.parseInt(props.get("db_timeout").toString()));
        p.setMinEvictableIdleTimeMillis(30000);
        p.setMinIdle(2);
        p.setMaxIdle(Integer.parseInt(props.get("db_maxIdle").toString()));
        p.setLogAbandoned(true);
        p.setRemoveAbandoned(true);
        p.setJdbcInterceptors(
          "org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
          "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
        ds = new DataSource();
        ds.setPoolProperties(p);
    }

    public Connection getConnection() throws SQLException {
        
        try {          
            return ds.getConnection();
        } catch (Exception ex) {
        	ex.printStackTrace();
        	ds = null;
        	try {
				init();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            logger.fatal("获得连接池连接失败！", ex);
            throw new SQLException("获得连接池连接失败");
        }    
    }
               
    public void destory() throws SQLException {
        if(ds != null){
            ds.notify();     // connection pool will be closed
        }
    }
    
}
